package org.zch.common.utils;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import java.util.List;

/**
 * 发送短信通知
 * 多发
 *List<String> mobiles = new ArrayList<>();
 *mobiles.add("15*******13");
 *mobiles.add("13*******27");
 *mobiles.add("17*******56");
 *String s= getSplitString(mobiles);
 */
public class SengSmsUtils {

    // 签名
    private static final String signName = "话唠用声音点亮生活";
    // 模板
    private static final String templateCode = "SMS_294121098";
    // 阿里云短信配置信息
    private static final String accessKeyId = "LTAI5tF1bcgf5PPqfKvfjH5U";
    private static final String accessKeySecret = "LsTfD2Iez6KjjaS9rwp3deUVhY3Q9g";
    private static final String REGION_ID = "cn-hangzhou";
    private static final String PRODUCT = "Dysmsapi";
    private static final String DOMAIN = "dysmsapi.aliyuncs.com";


    public static boolean sendSMS(String mobile,String mCode) {
        try {
            IClientProfile profile = DefaultProfile.getProfile(REGION_ID, accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint(REGION_ID, REGION_ID, PRODUCT, DOMAIN);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setMethod(MethodType.POST);
            // 手机号可以单个也可以多个（多个用逗号隔开，如：15*******13,13*******27,17*******56）
            request.setPhoneNumbers(mobile);
            request.setSignName(signName);
            request.setTemplateCode(templateCode);
            request.setTemplateParam("{\"code\":"+"'"+mCode+"'"+"}");
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if ((sendSmsResponse.getCode() != null) && (sendSmsResponse.getCode().equals("OK"))) {
                return true;
            } else {
                return false;
            }
        } catch (ClientException e) {
            return false;
        }
    }

    /**
     * 获取逗号分隔的拼接字符串
     */
    public static String getSplitString(List<String> str) {
        StringBuilder newS = new StringBuilder();
        if (str != null && str.size() > 0) {
            for (String s : str) {
                newS.append(s).append(",");
            }
        }
        if (newS.length() > 0){
            newS.deleteCharAt(newS.length() - 1);// 删除最后一个多余的逗号
        }

        return newS.toString();
    }
}
